package com.wbao.dianniu.tabstrip.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.listener.IJobStatusListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.JobStatusManager;
import com.wbao.dianniu.ui.ComRecruitActivity;
import com.wbao.dianniu.ui.CreateActivity;
import com.wbao.dianniu.ui.IPartInActivity;
import com.wbao.dianniu.ui.IReleaseActivity;
import com.wbao.dianniu.ui.IndustryAuthActivity;
import com.wbao.dianniu.ui.JobCollectActivity;
import com.wbao.dianniu.ui.JobDeliveryActivity;
import com.wbao.dianniu.ui.JobEditActivity;
import com.wbao.dianniu.ui.JobListActivity;
import com.wbao.dianniu.ui.JobPreviewActivity;
import com.wbao.dianniu.ui.KnowListActivity;
import com.wbao.dianniu.ui.MyKnowledgeActivity;
import com.wbao.dianniu.ui.OfflineActivity;
import com.wbao.dianniu.ui.RecReceiveActivity;
import com.wbao.dianniu.ui.RecruitManagerActivity;
import com.wbao.dianniu.update.ErrorDialogHelper;


/**
 * 发现
 *
 * @author yejianjun
 */
public class SecondFragment extends Fragment implements OnClickListener, IJobStatusListener {
    private TextView perResume, comRecurit, offlineAct;
    private TextView tvDelivery, tvEdit, tvPreview, tvJobClose, tvPostManager, tvReceive, tvRecord, tvRelease, tvIRelease, tvIPartIn;
    private JobStatusManager statusManger;
    // 定位模块相关
    private LocationClient mLocationClient = null;
    public BDLocationListener myListener;
    private boolean isFirstLoc = true;
    private Dialog dialog;
    private TextView tvKnowledge;
    private TextView myKnowledge;
    private int resumeStatus;
    private GlobalUserData userData;

    public static SecondFragment instance(Activity activity) {
        SecondFragment view = new SecondFragment();
        return view;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.second_fragment, null);
        userData = new GlobalUserData();
        resumeStatus = userData.getResumeStatus();
        initView(view);
        return view;
    }

    private void initManager() {
        statusManger = new JobStatusManager(getContext());
        statusManger.addStatusListener(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initManager();
        // 屏蔽定位
//        initLocation(getActivity());
    }

    private void initView(View view) {
        perResume = (TextView) view.findViewById(R.id.per_resume);
        comRecurit = (TextView) view.findViewById(R.id.company_recruit);
        offlineAct = (TextView) view.findViewById(R.id.offline_activity);
        tvDelivery = (TextView) view.findViewById(R.id.tv_delivery);
        tvEdit = (TextView) view.findViewById(R.id.tv_edit_job);
        tvPreview = (TextView) view.findViewById(R.id.tv_preview);
        tvJobClose = (TextView) view.findViewById(R.id.tv_job_close);
        tvPostManager = (TextView) view.findViewById(R.id.tv_post_manager);
        tvReceive = (TextView) view.findViewById(R.id.tv_resume_receive);
        tvRecord = (TextView) view.findViewById(R.id.tv_collect_record);
        tvRelease = (TextView) view.findViewById(R.id.tv_release_activity);
        tvIRelease = (TextView) view.findViewById(R.id.tv_i_released);
        tvIPartIn = (TextView) view.findViewById(R.id.tv_i_partin);
        tvKnowledge = (TextView) view.findViewById(R.id.knowledge_hall);
        myKnowledge = (TextView) view.findViewById(R.id.my_knowledge_tv);

        if (1 == resumeStatus) {
            Drawable drawable = getResources().getDrawable(R.drawable.find_open_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvJobClose.setCompoundDrawables(null, drawable, null, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.find_close_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvJobClose.setCompoundDrawables(null, drawable, null, null);
        }
        perResume.setOnClickListener(this);
        comRecurit.setOnClickListener(this);
        offlineAct.setOnClickListener(this);
        tvDelivery.setOnClickListener(this);
        tvEdit.setOnClickListener(this);
        tvPreview.setOnClickListener(this);
        tvJobClose.setOnClickListener(this);
        tvPostManager.setOnClickListener(this);
        tvReceive.setOnClickListener(this);
        tvRecord.setOnClickListener(this);
        tvRelease.setOnClickListener(this);
        tvIRelease.setOnClickListener(this);
        tvIPartIn.setOnClickListener(this);
        tvKnowledge.setOnClickListener(this);
        myKnowledge.setOnClickListener(this);
    }

    private void initLocation(Context context) {

        /*if (Build.VERSION.SDK_INT >= 23) {
            int checkSelfPermission = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                return;
            } else {
                System.out.println("权限允许。。。");
            }
        } else {
            System.out.println("权限允许。。。");
        }*/

        /*Acp.getInstance(mActivity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE).build(), new AcpListener() {
            @Override
            public void onGranted() {
                Notification.toast(getContext(),"权限允许");
            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(getContext(), permissions.toString() + "权限拒绝");
            }
        });*/

        // 定位初始化
        mLocationClient = new LocationClient(context);
        myListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null) {
                return;
            }
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                if (isFirstLoc) {
                    String city = location.getCity();
                    if (null != city) {
                        isFirstLoc = false;
                        GlobalContext.curLocation = city;
                    }
                }
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                if (isFirstLoc) {
                    String city = location.getCity();
                    if (null != city) {
                        isFirstLoc = false;
                        GlobalContext.curLocation = city;
                    }
                }
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                if (isFirstLoc) {
                    String city = location.getCity();
                    if (null != city) {
                        isFirstLoc = false;
                        GlobalContext.curLocation = city;
                    }
                }
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                Log.e("Location","TypeCriteriaException.......");
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                Log.e("Location","TypeCriteriaException.......");
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                Log.e("Location","TypeCriteriaException.......");
                mLocationClient.stop();
            }

        }

//        @Override
//        public void onConnectHotSpotMessage(String s, int i) {
//
//        }
    }

    @Override
    public void onClick(View v) {
        GlobalUserData userData = new GlobalUserData();
        switch (v.getId()) {
            case R.id.company_recruit:        //找工作
                Intent com_intent = new Intent();
                com_intent.setClass(getActivity(), ComRecruitActivity.class);
                startActivity(com_intent);
                break;
            case R.id.per_resume:                //	找人才
                Intent trial_intent = new Intent();
                trial_intent.setClass(getActivity(), JobListActivity.class);
                startActivity(trial_intent);
                break;
            case R.id.offline_activity:                //找活动
                Intent offline_intent = new Intent();
                offline_intent.putExtra(Const.BUNDLE_DATA, "" /*GlobalContext.curLocation*/);
                offline_intent.setClass(getActivity(), OfflineActivity.class);
                startActivity(offline_intent);
                break;
            case R.id.tv_delivery: // 投递记录
                Intent applyJobIntent = new Intent();
                applyJobIntent.setClass(getActivity(), JobDeliveryActivity.class);
                startActivity(applyJobIntent);
                break;
            case R.id.tv_edit_job: //简历编辑
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                    return;
                }
                Intent jobReleaseIntent = new Intent();
                jobReleaseIntent.setClass(getActivity(), JobEditActivity.class);
                startActivity(jobReleaseIntent);
                break;
            case R.id.tv_preview: //简历预览
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                    return;
                }

                if (!userData.getPerfectResume()) {
                    showPerfectAuth(getResources().getString(R.string.incomplete_Resume), JobEditActivity.class);
                    return;
                }
                Intent previewIntent = new Intent();
                previewIntent.setClass(getActivity(), JobPreviewActivity.class);
                startActivity(previewIntent);
                break;
            case R.id.tv_job_close: //简历隐藏
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                    return;
                }
                if (!userData.getPerfectResume()) {
                    showPerfectAuth(getResources().getString(R.string.incomplete_Resume), JobEditActivity.class);
                    return;
                }
                if (1 == resumeStatus) {
                    resumeStatus = 0;
                } else {
                    resumeStatus = 1;
                }
                userData.setResumeStatus(resumeStatus);
//                SharedPreferencedUtils.setInteger(getContext(),GlobalContext.RESUMESTATUS_PREFERENCES,resumeStatus);
                statusManger.jobStatus(GlobalContext.getAccountId(), resumeStatus);
                break;
            case R.id.tv_post_manager://岗位管理
                if (!GlobalContext.getIndustryAuthority()) {
                    showIndustryAuth(getResources().getString(R.string.incomplete_industry_auth_1));
                    return;
                }
                Intent applyRecruitIntent = new Intent();
                applyRecruitIntent.setClass(getActivity(), RecruitManagerActivity.class);
                startActivity(applyRecruitIntent);
                break;
            case R.id.tv_resume_receive://收到简历
                Intent receiveJob = new Intent();
                receiveJob.setClass(getActivity(), RecReceiveActivity.class);
                startActivity(receiveJob);
                break;
            case R.id.tv_collect_record://收藏记录
                Intent jobCollect = new Intent();
                jobCollect.setClass(getActivity(), JobCollectActivity.class);
                startActivity(jobCollect);
                break;
            case R.id.tv_release_activity://发布活动
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                    return;
                }
                if (!GlobalContext.getIndustryAuthority()) {
                    showIndustryAuth(getResources().getString(R.string.incomplete_industry_auth_2));
                    return;
                }
                Intent createIntent = new Intent();
                createIntent.setClass(getActivity(), CreateActivity.class);
                startActivity(createIntent);
                break;
            case R.id.tv_i_released://我发布的
                Intent releaseIntent = new Intent();
                releaseIntent.setClass(getActivity(), IReleaseActivity.class);
                startActivity(releaseIntent);
                break;
            case R.id.tv_i_partin://我参与的
                Intent partInIntent = new Intent();
                partInIntent.setClass(getActivity(), IPartInActivity.class);
                startActivity(partInIntent);
                break;
            case R.id.knowledge_hall:
                Intent knowIntent = new Intent();
                knowIntent.setClass(getActivity(), KnowListActivity.class);
                startActivity(knowIntent);
                break;
            case R.id.my_knowledge_tv:
                Intent myKnowIntent = new Intent();
                myKnowIntent.setClass(getActivity(), MyKnowledgeActivity.class);
                startActivity(myKnowIntent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onStatusFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusSuccess() {
        if (1 == resumeStatus) {
            Drawable drawable = getResources().getDrawable(R.drawable.find_open_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvJobClose.setCompoundDrawables(null, drawable, null, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.find_close_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvJobClose.setCompoundDrawables(null, drawable, null, null);
        }
    }

    /**
     * 显示行业认证弹出框
     */
    private void showIndustryAuth(String msg) {
        dialog = new Dialog(getContext(), R.style.custom_Dialog);
        Window win = dialog.getWindow();
        win.getDecorView().setPadding(3, 3, 3, 3);
        win.setGravity(Gravity.CENTER);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_message_dialog, null);
        Button okBtn = (Button) view.findViewById(R.id.custom_msg_ok);
        Button cancelBtn = (Button) view.findViewById(R.id.custom_msg_cancel);
        TextView message = (TextView) view
                .findViewById(R.id.custom_msg_message);
        message.setText(msg);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        okBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                // 跳转到行业认证界面
                Intent intent = new Intent();
                intent.setClass(getContext(), IndustryAuthActivity.class);
                startActivity(intent);
            }
        });
        cancelBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 显示完善资料弹出框
     */
    private void showPerfectAuth(String msg, final Class cls) {
        dialog = new Dialog(getContext(), R.style.custom_Dialog);
        Window win = dialog.getWindow();
        win.getDecorView().setPadding(3, 3, 3, 3);
        win.setGravity(Gravity.CENTER);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_message_dialog, null);
        Button okBtn = (Button) view.findViewById(R.id.custom_msg_ok);
        Button cancelBtn = (Button) view.findViewById(R.id.custom_msg_cancel);
        TextView message = (TextView) view
                .findViewById(R.id.custom_msg_message);
        message.setText(msg);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        okBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), cls);
                startActivity(intent);
            }
        });
        cancelBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    public void onStop() {
        if (null != mLocationClient) {
            mLocationClient.stop();
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (null != mLocationClient) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);
        }
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SecondFragment"); //统计页面，"MainScreen"为页面名称，可自定义
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SecondFragment");
    }


}